from mootdx.reader import Reader
import json
from db.save import Save
from db.read import DBReader
import traceback
# 全量读取通达信官方下载的数据包
# 初始化通达信文件读取类，D:/shlday目录里的文件夹结构要跟通达信一致 /vipdoc/sz/xxx
# C:/new_tdx/vipdoc/sz/lday/ 下是深圳的日k线数据
# C:/new_tdx/vipdoc/sh/lday/ 下是上海的日k线数据
reader = Reader.factory(market="std", tdxdir="G:/geek/tdx")  # 标准市场，全量数据目录
# reader = Reader.factory(market='ext', tdxdir='../fixtures') # 扩展市场

stockcode="600036"
stockname="招商银行"
pricetype = "2" #1-不复权，2-后复权，3-前复权
# 读取日数据
read = DBReader()
stocklist=read.get_stock_list()

save = Save()
conn=save.connect()
cursor = conn.cursor()

for item in stocklist:
    try:
        stockcode = item[0]
        stockname = item[1]
        daily = reader.daily(symbol=stockcode, adjust='hfq')

        # 将DataFrame的每一行转换为包含索引值的字典，存放在一个列表中
        for index_value, row_series in daily.iterrows():
            row_dict = row_series.to_dict()
            month=index_value.month
            day=index_value.day
            week = index_value.week
            monthstr = str(month)
            daystr = str(day)
            if month < 10:
                monthstr='0'+str(month)
            if day < 10:
                daystr = '0'+str(day)
            row_dict['year'] = index_value.year
            row_dict['month'] = month
            row_dict['day'] = day
            row_dict['week'] = week
            row_dict['date'] = str(index_value.year)+'-'+monthstr+'-'+daystr
            row_dict['datetime'] = row_dict['date'] + "T15:00:00"
            row_dict['id']=str(index_value.year) + monthstr + daystr + pricetype + stockcode
            row_dict['stockcode'] = stockcode
            row_dict['stockname'] = stockname
            save.exec(row_dict, "stock_day_info", conn, cursor)

        print("save success: "+ stockcode +stockname)
    except:
        print("error stockcode:" + stockcode)
        with open('insert_error_stockcode_list.txt', 'a+', encoding='utf-8') as f2:
            f2.writelines(stockcode+","+stockname+"\n")
            f2.close()
        traceback.print_exc()
        conn.rollback()
cursor.close()
conn.close()
